import React, { Component } from "react";
import { Form, Icon, Input, Button, Alert, message, notification } from "antd";
import { loginApi, getPublickeyApi, updateUserApi } from "../js/api.js";
import { iconFontUrl } from "../js/config.js";
import '../css/pwd.css';
import '../css/custom.css'


const FormItem = Form.Item;
const IconFont = Icon.createFromIconfontCN({
    scriptUrl: iconFontUrl,
});


class updatePassword extends Component {
    constructor(props) {
        super(props);
        this.state = {
            msg: "",
            alertVisible: false,
            pwd: "",
            confirmLoading:false
        };
    }
    componentWillReceiveProps(props) {

    }

    componentDidMount() {

    }

    //密码强弱判断
    judgePassword(password) {
        var reg = /^[0-9]{6,16}$|^[a-zA-Z]{6,16}$/   //全是数字或全是字母     6-16个字符   弱
        var reg2 = /^[A-Za-z0-9]{6,16}$/ //数字、26个英文字母      6-16个字符   中
        // var reg3 = /(?!^(\d+|[a-zA-Z]+|[~!@#$%^&*?]+)$)^[\w~!@#$%^&*?]{6,16}$/ // 由数字、26个英文字母或者特殊字符组成的字符串  6-16个字符  强
        //数字+字母，数字+特殊字符，字母+特殊字符，数字+字母+特殊字符(所有字符，兼容空格)组合，而且不能是纯数字，纯字母，纯特殊字符
        // var reg3 = /^(?![\d]+$)(?![a-zA-Z]+$)(?![^\da-zA-Z]+$).{6,16}$/ 

        // 最终版 限定特殊字符~`!@#%^&*()\\_+\-={}|'";:,./<>? 不能有空格
        var reg3 = /^(?![\d]+$)(?![a-zA-Z]+$)(?![~`!@#%^&*()\\_+\-={}|'";:,./<>?]+$)[\da-zA-Z~`!@#%^&*()\\_+\-={}|'";:,./<>?]{6,16}$/
    
        //字母、数字、特殊字符最少2种组合（不能有中文和空格）
        // var reg3 = /^(?!.*[\u4E00-\u9FA5\s])(?!^[a-zA-Z]+$)(?!^[\d]+$)(?!^[^a-zA-Z\d]+$)^.{6,16}$/
        if (password.match(reg)) {
            return 1
        } else if (password.match(reg2)) {
            return 2
        } else if (password.match(reg3)) {
            return 3
        } else {
            if(password.length <6){
                return 0
            }
        }

    }

    handleSubmit = e => {
        e.preventDefault();
        this.props.form.validateFields((err, values) => {
            if (!err) {
                var flag = this.judgePassword(values.pwd)
                if (values.pwd != values.repwd) {
                    this.setState({
                        alertVisible: true,
                        msg: "两次输入密码不一致,请重新输入!"
                    });
                    // message.error("两次输入密码不一致,请重新输入!", 5)
                } else if (values.pwd == "" || values.repwd == "") {
                    this.setState({
                        alertVisible: true,
                        msg: "密码不可为空,请重新输入!"
                    });
                    // message.error("密码不可为空,请重新输入!", 5)
                } else {
                    if (flag == 0 || flag == undefined) {
                        console.log("----------------密码不符合规则，请重新设置！", values.pwd)
                        this.setState({
                            msg: "密码不符合规则，请重新设置！",
                            alertVisible: true
                        })
                        // message.error("密码包含非法字符，请重新设置！", 5)
                    } else if (flag == 1) {
                        console.log("----------------密码较弱，请重新设置", values.pwd)
                        this.setState({
                            msg: "密码较弱，请重新设置！",
                            alertVisible: true
                        })
                        // message.error("密码较弱，请重新设置！", 5)
                    } else {
                        this.setState({
                            confirmLoading: true,
                        });
                        console.log("----------------设置成功", values.pwd)
                        var username = sessionStorage.getItem("username");
                        values.department = sessionStorage.getItem("departmentId");
                        values.password = values.pwd
                        updateUserApi(username, values)
                            .then((res) => {
                                if (res.data == "success") {
                                    this.setState({
                                        msg: "",
                                        alertVisible: false,
                                        confirmLoading:false
                                    })
                                    this.openNotificationWithIcon('bottomRight')
                                    this.props.history.push("/")
                                } else if (res.data == "fail") {
                                    this.setState({
                                        alertVisible: true,
                                        msg: "修改失败,请检查信息或稍后再试!",
                                        confirmLoading:false
                                    });
                                }
                            })

                    }
                }

            }
        });
    }

    handleClose = () => {
        this.setState({
            msg: "",
            alertVisible: false
        })
    }

    openNotificationWithIcon = placement => {
        notification.success({
            message: '密码设置成功',
            description:
                '当前密码已重新修改，密码强度较为安全，请重新登录！',
            placement
        })
    }

    inputChange = (event) => {
        this.setState({
            pwd: event.target.value,
            msg: "",
            alertVisible: false
        })
        if (event.target.value == "") {
            document.getElementById("lv").style.display = "none";
            document.getElementById("tips").style.display = "none";
            document.getElementById("tips2").style.display = "none";
        } else {
            var flag = this.judgePassword(event.target.value);
            console.log(flag)
            document.getElementById("lv").style.display = "";
            document.getElementById("tips").style.display = "";
            if (flag == 1) {
                document.getElementById("lv1").style.borderTopColor = "red";
                document.getElementById("lv2").style.borderTopColor = "gainsboro";
                document.getElementById("lv3").style.borderTopColor = "gainsboro";
                document.getElementById("lv4").style.display = "none";
                document.getElementById("tips").style.color = "#A8280E";
                document.getElementById("tips2").style.display = "none";
            } else if (flag == 2) {
                document.getElementById("lv1").style.borderTopColor = "gainsboro";
                document.getElementById("lv2").style.borderTopColor = "red";
                document.getElementById("lv3").style.borderTopColor = "gainsboro";
                document.getElementById("lv").style.display = "flex";
                document.getElementById("lv").style.width = "100%";
                document.getElementById("lv4").style.display = "";
                document.getElementById("tips").style.display = "none";
                document.getElementById("tips2").style.display = "none";
            } else if (flag == 3) {
                document.getElementById("lv1").style.borderTopColor = "gainsboro";
                document.getElementById("lv2").style.borderTopColor = "gainsboro";
                document.getElementById("lv3").style.borderTopColor = "red";
                document.getElementById("lv").style.display = "flex";
                document.getElementById("lv").style.width = "100%";
                document.getElementById("lv4").style.display = "";
                document.getElementById("tips").style.display = "none";
                document.getElementById("tips2").style.display = "none";
            } else if(flag == 0){
                document.getElementById("lv").style.display = "none";
                document.getElementById("tips").style.display = "none";
                document.getElementById("tips2").style.display = "none";
            }else{
                document.getElementById("tips").style.display = "none";
                document.getElementById("tips2").style.color = "#A8280E";
                document.getElementById("tips2").style.display = "";
                document.getElementById("lv").style.display = "none";
            }
        }

    }
    onClickInput = () => {
        document.getElementById("tips").style.display = "";
        document.getElementById("tips").style.color = "";
    }

    render() {
        const { getFieldDecorator } = this.props.form;
        return (
            <div className="judgePwd-background">
                <div className="judgePwd">
                    <div style={{
                        height: "430px",
                        width: "520px",
                        display: "flex",
                        justifyContent: "center",
                        // alignItems: "center",
                        marginTop: "20px"
                    }}>
                        <Form onSubmit={this.handleSubmit.bind(this)} className="login-form">
                            <div style={{ marginTop: '0.5rem', marginLeft: '-3rem', fontWeight: 550, fontSize: 18 
                             , marginRight: '-1rem', marginBottom: '1.5rem'}}>
                                <IconFont type='icon-risk' style={{ fontSize: '2.5em', marginLeft: '1.5rem' }} />
                                {sessionStorage.getItem("judgePassword")==1?
                                (<span>当前密码过短，请重新修改密码</span>):null}
                                {sessionStorage.getItem("judgePassword")==2?
                                (<span>当前密码过长，请重新修改密码</span>):null}
                                {sessionStorage.getItem("judgePassword")==3?
                                (<span>当前密码强度弱，请重新修改密码</span>):null}
                                {sessionStorage.getItem("judgePassword")==4?
                                (<span>当前密码存在安全风险，请重新修改密码</span>):null}
                            </div>
                            <FormItem>
                                {getFieldDecorator("pwd", {
                                    rules: [{
                                        required: true,
                                        message: '请输入新密码！',
                                    }]
                                })(
                                    <Input
                                        size="large"
                                        prefix={
                                            <Icon type="lock" style={{ color: "rgba(0,0,0,.25)" }} />
                                        }
                                        type="password"
                                        placeholder="请输入新密码"
                                        maxLength={16}
                                        minLength={6}
                                        onClick={this.onClickInput}
                                        onChange={this.inputChange}
                                        value={this.state.pwd}
                                    />
                                )}
                            </FormItem>
                            <div id="tips" style={{
                                display: 'none', fontWeight: 500,
                                marginTop: '-0.5rem', marginBottom: '0.5rem', marginLeft: '-3.8rem'
                            }} >
                                6-16字符,字母、数字和特殊字符中的2种组合
                            </div>
                            <div id="tips2" style={{
                                display: 'none', fontWeight: 500,
                                marginTop: '-0.2rem', marginBottom: '0rem', marginLeft: '-12rem'
                            }} >
                                密码不符合规范！
                            </div>
                            <FormItem>
                                <div className="mm-btm" id="lv" style={{ display: 'none' }}>
                                    <div id="lv1">弱</div>
                                    <div id="lv2">中</div>
                                    <div id="lv3">强</div>
                                    <div id="lv4" style={{ display: 'none' }}>
                                        <IconFont type='icon-tongguo2' style={{ fontSize: '2.5em', marginLeft: '1.5rem' }} />
                                    </div>
                                </div>
                            </FormItem>
                            <FormItem>
                                {getFieldDecorator("repwd", {
                                    rules: [{
                                        required: true,
                                        message: '请重复输入新密码！',
                                    }]
                                })(
                                    <Input
                                        size="large"
                                        prefix={
                                            <Icon type="lock" style={{ color: "rgba(0,0,0,.25)" }} />
                                        }
                                        type="password"
                                        placeholder="请重复密码"
                                        maxLength={16}
                                        minLength={6}
                                    />
                                )}
                            </FormItem>
                            {
                                this.state.alertVisible ?
                                    (
                                        <Alert message={this.state.msg} type="error" closable afterClose={this.handleClose.bind(this)} />
                                    ) : null
                            }
                            <FormItem>
                                <Button
                                    type="primary"
                                    htmlType="submit"
                                    className="login-form-button"
                                    loading={this.state.confirmLoading}
                                    style={{ marginTop: '1rem' }}>
                                    修改
                                </Button>
                            </FormItem>
                        </Form>
                    </div>
                </div>
                <div style={{ width: "100%", textAlign: "left", position: "fixed", zIndex: 3, bottom: 0, left: "5%" }}>

                    <p style={{ textAlign: "left", height: 20, color: "#ffffff" }}>
                        CopyRight{"   "}  梯度安全网格版权所有 {"  "}
                        <a href="http://beian.miit.gov.cn/" target="_blank" style={{
                            display: "inline-block",
                            textDecoration: "none",
                            color: "#ffffff"
                        }}> 浙ICP备19000794-1号</a>
                    </p>


                    <p style={{ textAlign: "left", height: 20, color: "#ffffff" }}>
                        <img src="../img/beiantubiao.png" style={{ display: "inline" }} />
                        < a target="_blank" href="http://www.beian.gov.cn/portal/registerSystemInfo?recordcode=33010802010966"
                            style={{ display: 'inline', textDecoration: 'none', }}>浙公网安备 33010802010966号</a></p>


                </div>
            </div>
        );
    }
}

const UpdatePassword = Form.create()(updatePassword);

export { UpdatePassword };